package com.kd.juhaowan.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;


import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallbackProxy;
import com.hjq.toast.ToastUtils;
import com.kd.juhaowan.R;
import com.kd.juhaowan.http.api.LoginApi;
import com.kd.juhaowan.http.api.PhoneAccountListApi;
import com.kd.juhaowan.http.api.PhoneCodeApi;
import com.kd.juhaowan.http.model.HttpData;
import com.kd.juhaowan.http.model.HttpListData;
import com.kd.juhaowan.model.LoginUser;
import com.kd.juhaowan.ui.adapter.SpinnerListAdapter;
import com.kd.juhaowan.ui.listener.OnItemRemoveListener;
import com.kd.juhaowan.utils.LogUtil;
import com.kd.juhaowan.utils.MsgCountDown;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginAccountActivity extends BaseActivity{

    private int logtype = 1;
    @BindView(R.id.login_account_phone)
    TextView loginSwich;
    @BindView(R.id.login_title)
    TextView titleView;
    @BindView(R.id.login_account_account)
    EditText registAccount;
    @BindView(R.id.login_account_pwd)
    EditText registPwd;
    @BindView(R.id.login_spinner)
    ImageButton loginSpiner;
    @BindView(R.id.regist_phone_code_get)
    TextView loginCode;
    @BindView(R.id.accout_title)
    TextView accountTitle;
    @BindView(R.id.password_title)
    TextView passwordTitle;

    private SpinnerListAdapter mPopupWindowAdatper;
    private ListPopupWindow mPopupWindow;
    private List<LoginUser> mAdapterData = new ArrayList<LoginUser>();
    private ActivityResultLauncher<Intent> register;

    @Override
    protected void reInitDate() {

    }

    @OnClick(R.id.login_spinner)
    public void onSpinnerClick(View view){
        openSpinnerPopup(loginSpiner);
    }

    @OnClick(R.id.login_account_forget)
    public void onForgetClick(View view){
        startActivity(new Intent(LoginAccountActivity.this,ForgetActivity.class));
    }

    @OnClick(R.id.regist_phone_code_get)
    public void getPhoneCode(View view){
        String account = registAccount.getText().toString().trim();
        if(TextUtils.isEmpty(account)){
            ToastUtils.show("请输入手机号");
            return;
        }
        EasyHttp.post(this).api(new PhoneCodeApi(account,"get_code_account")).request(new HttpCallbackProxy<HttpData<LoginUser>>(this){
            @Override
            public void onHttpSuccess(HttpData<LoginUser> result) {
                super.onHttpSuccess(result);
                ToastUtils.show("获取验证码成功");
                MsgCountDown.setCurrentTime();
                updateSmsCount();
            }
        });
    }

    private void updateSmsCount() {
        if (isFinishing()||isDestroyed()) {
            return;
        }

        int value = (int) ((System.currentTimeMillis() - MsgCountDown.getLastTime()) / 1000);
        if (value > 59) {
            loginCode.setEnabled(true);
            loginCode.setText("重新发送");
//            loginCode.setTextColor(Color.parseColor("#ffffff"));
        } else {
//            reGetCode.setTextColor(Color.parseColor("#a39dce"));
//			reGetCode.setTextColor(ViewUtil.getColorRs(activity,"fjd_white"));
            loginCode.setEnabled(false);
            loginCode.setText((60 - value) + "s");
            loginCode.postDelayed(new Runnable() {

                @Override
                public void run() {
                    updateSmsCount();
                }
            }, 1000);
        }
    }

    private void openSpinnerPopup(View view) {
        if (view.isSelected()) {
            view.setSelected(false);
            destroyAndDismissSpinnerPopup();
        } else {
            view.setSelected(true);
            createAndShowSpinnerPopup();
        }
    }


    private void destroyAndDismissSpinnerPopup() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }

    private void createAndShowSpinnerPopup() {

        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.edit_bg);
        mPopupWindowAdatper = new SpinnerListAdapter(mAdapterData.subList(1, mAdapterData.size()));
        mPopupWindow = new ListPopupWindow( this);
        mPopupWindow.setBackgroundDrawable(drawable);
        mPopupWindow.setAdapter(mPopupWindowAdatper);
        mPopupWindow.setModal(true);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                loginSpiner.setSelected(false);
            }
        });
        mPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object item = parent.getItemAtPosition(position);
                if (item instanceof LoginUser) {
                    registAccount.setText(((LoginUser) item).getAccount());
                    registPwd.setText(((LoginUser) item).getPassword());
                    registAccount.setSelection(((LoginUser) item).getUsername().length());
                    destroyAndDismissSpinnerPopup();
                    regenerateAdapteData(position + 1);
                }
            }
        });

        mPopupWindowAdatper.setOnItemRemoveListener(new OnItemRemoveListener() {
            @Override
            public void OnItemRemove(View view, int position) {
                LoginUser info = mPopupWindowAdatper.removeItem(position);

                manager.deleteUserAccount(info);
                mAdapterData.remove(info);
                loginSpiner.setEnabled(mAdapterData.size() > 1);
                if (mAdapterData.size() > 1) {
                    mPopupWindowAdatper.notifyDataSetChanged();
                } else {
                    mPopupWindowAdatper.notifyDataSetChanged();
                    destroyAndDismissSpinnerPopup();
                }
            }
        });

        mPopupWindow.setAnchorView((LinearLayout)loginSpiner.getParent());
        mPopupWindow.show();
        if (mPopupWindow.isShowing()) {
            ListView listview = mPopupWindow.getListView();
            listview.setDivider(new ColorDrawable(0x80ffffff));
            listview.setDividerHeight(1);
        }
    }

    private void regenerateAdapteData(int position) {
        final int adapterSize = mAdapterData.size();
        position = position >= adapterSize ? adapterSize - 1 : position;
        if (position > 0) {
            LoginUser accountInfo = mAdapterData.remove(position);
            mAdapterData.add(0, accountInfo);
        }
    }

    @Override
    protected int getViewLayoutResourceId() {
        return R.layout.activity_login_account;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isPay = getIntent().getBooleanExtra("isPay",false);
        isAuth = getIntent().getBooleanExtra("isAuth",false);
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                LogUtil.debugLog( "onActivityResult: _____" + result);
                if (result != null) {

                    if (result.getResultCode() == Activity.RESULT_OK) {
                        gotoMainActivity();

                    }
                }
            }
        });

        initData();

    }
//    private boolean isFormRegist = false;
    private boolean isAuth = false;
    private boolean isPay =false;
    private void initData(){
//        showLoadingDialog();

        int loType= manager.readLastLoginType();
        List<LoginUser> infos = manager.readAllUserAccountInfo();
//        List<LoginUser> infosNew = new ArrayList<>();
        if(infos!=null&&infos.size()>0){

//
            for(int i =0;i<infos.size();i++){
                if(!TextUtils.isEmpty(infos.get(i).getPassword())){
//                    infosNew.add(infos.get(i));
                    LogUtil.debugLog(infos.get(i).getAccount());
                    LogUtil.debugLog(infos.get(i).getPassword());
                    if(infos.get(i).isPhoneAccount()){
                        phonelist.add(infos.get(i));
                        accountlist.add(infos.get(i));
                    }else{
                        accountlist.add(infos.get(i));
                    }
                }

            }
        }else{
//            if(!isFormRegist){
//                gotoRegist(null);
//            }
        }
        registAccount.setText(accountlist.isEmpty()?"":accountlist.get(0).getAccount());
        registPwd.setText(accountlist.isEmpty()?"":accountlist.get(0).getPassword());
        initAdapterData();
        if(loType!=1){
            changeLoginType();
        }

//        if(manager.readAutoLogin()&&accountlist.size()>0){
//
//            LoginUser user = accountlist.get(0);
//            AutoLoginDialog dialog = new AutoLoginDialog(LoginAccountActivity.this,user.getAccount());
//            dialog.show();
//            EasyHttp.post(this).api(new AutoLoginApi(user.getRefresh_token())).request(new HttpCallbackProxy<HttpData<LoginUser>>(this){
//                @Override
//                public void onHttpSuccess(HttpData<LoginUser> result, boolean cache) {
//                    super.onHttpSuccess(result, cache);
//                    LoginUser loginUser = result.getData();
////                        LogUtil.debugLog(result.getData().getAccess_token());
////                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
//                    user.setAccess_token(loginUser.getAccess_token());
//                    user.setRefresh_token(loginUser.getRefresh_token());
//                    manager.saveUserAccount(user);
//                    manager.writeAutoLogin(true);
//                    manager.writeLastLoginType(1);
//                    manager.saveCurrentLoginUserTickit(user.getAccess_token());
////                    cancelLoadingDialog();
//
//                    gotoMainActivity();
//                }
//
//                @Override
//                public void onHttpEnd(Call call) {
//                    super.onHttpEnd(call);
//                    dialog.dismiss();
//                }
//            });
//        }else {
////            cancelLoadingDialog();
//        }
    }


    List<LoginUser> accountlist = new ArrayList<>();
    List<LoginUser> phonelist = new ArrayList<>();

    private void changeLoginType(){
        if(logtype==1){
            logtype=2;
            titleView.setText("手机号登录");
            loginSwich.setText("账号登录");
            accountTitle.setText("手机号码");
            passwordTitle.setText("验证码");
            registAccount.setHint("请输入手机号");
            loginCode.setVisibility(View.VISIBLE);
            registPwd.setHint("请输入验证码");
            if(phonelist.size()>0){
                registAccount.setText(phonelist.get(0).getAccount());
                registPwd.setText(phonelist.get(0).getPassword());
            }else {
                registAccount.setText("");
                registPwd.setText("");
            }
        }else{
            logtype=1;
            loginCode.setVisibility(View.GONE);
            loginSwich.setText("手机号登录");
            titleView.setText("账号登录");
            accountTitle.setText("账号");
            passwordTitle.setText("密码");
            registAccount.setHint("请输入账号");
            registPwd.setHint("请输入密码（6-20个字符）");
            if(accountlist.size()>0){
                registAccount.setText(accountlist.get(0).getAccount());
                registPwd.setText(accountlist.get(0).getPassword());
            }else{
                registAccount.setText("");
                registPwd.setText("");
            }

        }
        initAdapterData();
    }

    private void initAdapterData() {
        mAdapterData.clear();
        mAdapterData.addAll(accountlist);

        if (!mAdapterData.isEmpty()) {
            loginSpiner.setEnabled(mAdapterData.size() > 1);
        } else {
            loginSpiner.setEnabled(false);
        }
    }

    private void gotoMainActivity(){
        if(getIntent().getBooleanExtra("isLogout",false)){
            startActivity(new Intent(this,MainActivity.class));
        }else {
            setResult(RESULT_OK);
            finish();
        }

//        finish();
//        if(isAuth){
//            startActivity(new Intent(this,AuthActivity.class));
//        }else if(isPay){
//            startActivity(new Intent(this,PlatFormCoinActivity.class));
//        }
//        else{
//            startActivity(new Intent(this,MainActivity.class));
//        }
    }

    @OnClick(R.id.login_account_register)
    public void gotoRegist(View view){
        Intent in = new Intent(LoginAccountActivity.this,RegistActivity.class);
        in.putExtra("isAuth",isAuth);
        in.putExtra("isPay",isPay);
        register.launch(in);
//        startActivity(in);
//        finish();
    }
    @OnClick(R.id.login_account_phone)
    public void gotoPhoneLogin(View view){
        changeLoginType();
    }

    @OnClick(R.id.login_confirm)
    public void onLoginClick(View view){
        String account = registAccount.getText().toString().trim();
        String pwd = registPwd.getText().toString().trim();
        if(TextUtils.isEmpty(account)){
            Toast.makeText(LoginAccountActivity.this,logtype==1?"请输入账号":"请输入手机号",Toast.LENGTH_SHORT).show();
            return;
        }else if (TextUtils.isEmpty(pwd)){
            Toast.makeText(LoginAccountActivity.this,logtype==1?"请输入密码":"请输入验证码",Toast.LENGTH_SHORT).show();
            return;
        }else{
            if(logtype==1){
                EasyHttp.post(this).api(new LoginApi(account,pwd,"account")).request(new HttpCallbackProxy<HttpData<LoginUser>>(this){
                    @Override
                    public void onHttpSuccess(HttpData<LoginUser> result, boolean cache) {
                        super.onHttpSuccess(result, cache);
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                        ToastUtils.show("登录成功");
                        LoginUser user = result.getData();
                        user.setAccount(account);
                        user.setPassword(pwd);
                        user.setPhoneAccount(false);
                        manager.saveUserAccount(user);
                        manager.writeAutoLogin(true);
                        manager.writeLastLoginType(1);
                        manager.saveCurrentLoginUserTickit(user.getAccess_token());
                        gotoMainActivity();
                    }
                });
            }else{
                EasyHttp.post(this).api(new PhoneAccountListApi(account,pwd)).request(new HttpCallbackProxy<HttpListData<LoginUser>>(this){
                    @Override
                    public void onHttpSuccess(HttpListData<LoginUser> result, boolean cache) {
                        super.onHttpSuccess(result, cache);
//                        LogUtil.debugLog(result.getData().getAccess_token());
//                        Toast.makeText(AccountLoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                        List<LoginUser> users = result.getData().getList();

                        if(users==null||users.size()==0){
                            ToastUtils.show("当前手机号未绑定账号");
                            return;
                        }
//                        if(users.size()==1){
//
//                        }
                        for (int i=0;i<users.size();i++) {
                            users.get(i).setToken(result.getData().getToken());
                        }
                        ArrayList<LoginUser> buildrUsers = new ArrayList<>();
                        buildrUsers.addAll(users);
                        Intent intent=new Intent(LoginAccountActivity.this,PhoneLoginAccountActivity.class);
                        intent.putExtra("user",buildrUsers);
                        intent.putExtra("isForget",false);
                        intent.putExtra("phone",account);

                        register.launch(intent);

                    }
                });


            }
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if(getIntent().getBooleanExtra("isLogout",false)){
                gotoMainActivity();
                return true;
            }
//            // 关闭应用程序
//            //finish();
//            // 返回桌面操作
//            Intent home = new Intent(Intent.ACTION_MAIN);
//            home.addCategory(Intent.CATEGORY_HOME);
//            startActivity(home);


        }
        return super.onKeyDown(keyCode, event);
    }
}
